///////////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
#include <Scene/Culling/FrustumCuller.h>
#include <Scene/Object.h>
#include <Math/Vec3f.h>
#include <Scene/Culling/Frustum.h>
#include <Scene/SceneManager.h>
#include <Scene/Camera/Camera.h>
#include <Model/Mesh.h>
#include <Scene/Culling/Sphere.h>

//-----------------------------------------------------------------------------

FrustumCuller::FrustumCuller()
{
	m_frustum = MGL_NEW Frustum();
}

//-----------------------------------------------------------------------------

FrustumCuller::~FrustumCuller()
{
	SAFE_DEL( m_frustum );
}

//-----------------------------------------------------------------------------

void		FrustumCuller::Update( SceneManager* scene )
{
	Camera* cam = scene->GetCamera();
	m_frustum->setCamInternals( cam->GetFov(), cam->GetAspectRatio(), cam->GetNear(), cam->GetFar() );
	m_frustum->setCamDef( cam->getPosition(), cam->GetForward() + cam->getPosition(), cam->GetUp() );
	m_camView = cam->getViewMatrix();
}

//-----------------------------------------------------------------------------

//#include <Math/Vec4f.h>
bool		FrustumCuller::ShouldDrawObject( Object* obj )
{
	//Mesh* m = NULL;
	//AABBox* b = NULL;
	//Sphere* s = NULL;
	//for( u8 i = 0; i < obj->GetMeshCount(); i++ )
	//{
	//	m = obj->GetMesh(i);
	//	if( m->HasBoundingElement() )
	//	{
	//		b = m->GetOBB();
	//		s = m->GetBoundingSphere();
	//		if( b )
	//		{
	//			return m_frustum->isAABBoxInFrustum( *b ) != Frustum::OUTSIDE;
	//		}
	//		else if( s )
	//		{
	//			//return m_frustum->isSphereInFrustum( s->getCenter(), s->getRadius() ) != Frustum::OUTSIDE;

	//			return m_frustum->isSphereInFrustum( s->getCenter() * obj->GetAbsoluteTransform(), s->getRadius() * obj->getScale().x ) != Frustum::OUTSIDE;

	//			//Vec4f x(s->getCenter());
	//			//x *= obj->getScale().x;
	//			//x.w = 1;
	//			//x *= obj->GetAbsoluteTransform();
	//			//Vec3f y;
	//			//y.x = x.x;
	//			//y.y = x.y;
	//			//y.z = x.z;
	//			//return m_frustum->isSphereInFrustum( y, s->getRadius() * obj->getScale().x ) != Frustum::OUTSIDE;
	//		}

	//	}
	//}

	return m_frustum->isPointInFrustum( obj->getPosition() * m_camView ) != Frustum::OUTSIDE;
}

//-----------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
